USE SAS
GO

IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'InsUpdNotes')
	BEGIN
		DROP  Procedure  dbo.InsUpdNotes
	END
GO

CREATE Procedure dbo.InsUpdNotes (
	@NOTEID					VARCHAR(10)
,	@NOTESOURCEGUID			VARCHAR(100)
,	@SOURCEID				VARCHAR(10)		= ''
,	@NOTE					VARCHAR(MAX)	= ''
,	@USERID					VARCHAR(10)		= '1'	-- ADMIN USER
,	@NOTETYPE				VARCHAR(10)		= '3'	-- PARTNER
-- BELOW PARAMETERS ARE CURRENTLY HARDCODED
)
AS
BEGIN
	
	IF EXISTS(SELECT 1 FROM TR_NOTE WHERE NoteID = CAST(@NOTEID AS INT))
	BEGIN		-- UPDATE
		UPDATE TR_NOTE
		SET NoteText	= @NOTE
		,	ChangedBy	= @USERID
		,	ChangeDate	= GETDATE()
		WHERE
			NoteID		= @NOTEID
		AND	CAST(SourceGUID	AS VARCHAR(100)) = @NOTESOURCEGUID
	END
	ELSE
	BEGIN		-- INSERT 
		SELECT @NOTEID	= ISNULL(MAX(NoteID), 0) +1 FROM TR_NOTE

		INSERT INTO TR_NOTE (NoteId,NoteSource,NoteType,NoteText,
							CreatedBy,CreateDate,ChangedBy,ChangeDate,SourceGuid)
		VALUES(
			@NOTEID			--NoteId
		,	@SOURCEID		--NoteSource
		,	@NOTETYPE		--NoteType
		,	@NOTE			--NoteText
		,	@USERID			--CreatedBy
		,	GETDATE()		--CreateDate
		,	@USERID			--ChangedBy
		,	GETDATE()		--ChangeDate
		,	@NOTESOURCEGUID	--SourceGuid
		)
	END
END
GO
